﻿using EasyOAuth.Entity.Dto.Request;
using EasyOAuth.Entity.Dto.Result;
using EasyOAuth.Entity.Table;
using EasyOAuth.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace EasyOAuth.Controllers
{
    [Route("jwt/user")]
    [ApiController]
    public class JwtUserController : JwtOAuthController
    {
        UserService _service;

        IUserSession _session;

        IConfiguration _configuration;

        /// <summary>
        /// 用户
        /// </summary>
        /// <param name="service"></param>
        public JwtUserController(UserService service, IUserSession session, IConfiguration configuration)
        {
            _service = service;
            _session = session;
            _configuration = configuration;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("login"), AllowAnonymous]
        public UserLoginResult Login(UserLoginRequest request)
        {
            var securityKey = _configuration.GetValue<string>("Jwt:SecurityKey") ?? string.Empty;
            var validAudience = _configuration.GetValue<string>("Jwt:ValidAudience");

            var claims = new[]
                {
                    new Claim("ID","10000"),
                    new Claim("EFDID","1")
                };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: validAudience,
                audience: validAudience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return new UserLoginResult()
            {
                Name = "jwt to name",
                Token = token
            };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("info")]
        public Dictionary<string, string> GetInfo()
        {
            return _session.Get();
        }
    }
}
